import request from '../js/request.js';
import { setToken } from '../utils/auth.js';

// 自定义Base64编码函数
function customBtoa(str) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  let output = '';
  for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {
    charCode = str.charCodeAt(i += 3/4);
    block = block << 8 | charCode;
  }
  return output;
}

// 管理员登录方法 - 用于获取有权限的token
export const adminLogin = () => {
  const data = {
    username: 'admin',
    password: 'YehdBPev',
    grant_type: 'password',
    scope: 'server'
  };
  
  // 使用自定义的Base64编码函数
  const base64Auth = 'Basic ' + customBtoa('pig:pig');
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: 'http://localhost:9999/auth/oauth2/token',
      method: 'POST',
      data: data,
      header: {
        'Authorization': base64Auth,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (response) => {
        console.log('管理员登录成功', response);
        
        if (response.data && response.data.access_token) {
          setToken(response.data.access_token);
          console.log('已保存token:', response.data.access_token);
          resolve(response.data);
        } else {
          console.error('响应中缺少access_token');
          reject(new Error('响应中缺少access_token'));
        }
      },
      fail: (error) => {
        console.error('管理员登录失败', error);
        reject(error);
      }
    });
  });
};